import React, { useState, useRef } from 'react';

interface SVGMagnifierTooltipProps {
  children: React.ReactNode;
  imageUrl: string;
  title: string;
  username?: string;
}

const SVGMagnifierTooltip: React.FC<SVGMagnifierTooltipProps> = ({ 
  children, 
  imageUrl, 
  title, 
  username 
}) => {
  const [isVisible, setIsVisible] = useState(false);
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const containerRef = useRef<SVGGElement>(null);

  const handleMouseEnter = (e: React.MouseEvent) => {
    setIsVisible(true);
    updatePosition(e);
  };

  const handleMouseMove = (e: React.MouseEvent) => {
    if (isVisible) {
      updatePosition(e);
    }
  };

  const handleMouseLeave = () => {
    setIsVisible(false);
  };

  const updatePosition = (e: React.MouseEvent) => {
    const rect = (e.currentTarget as SVGElement).getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    
    // 调整位置以避免超出视口
    let adjustedX = x + 20;
    let adjustedY = y - 100;
    
    if (adjustedX + 200 > window.innerWidth) {
      adjustedX = x - 220;
    }
    if (adjustedY < 0) {
      adjustedY = y + 20;
    }
    
    setPosition({ x: adjustedX, y: adjustedY });
  };

  return (
    <g
      ref={containerRef}
      onMouseEnter={handleMouseEnter}
      onMouseMove={handleMouseMove}
      onMouseLeave={handleMouseLeave}
      style={{ cursor: 'pointer' }}
    >
      {children}
      
      {isVisible && (
        <foreignObject 
          x={position.x} 
          y={position.y} 
          width="200" 
          height="150"
          style={{ 
            pointerEvents: 'none',
            zIndex: 1000
          }}
        >
          <div className="bg-base-100 rounded-lg shadow-xl border border-primary p-3 max-w-[200px]">
            <img 
              src={imageUrl} 
              alt={title}
              className="w-full h-20 object-cover rounded mb-2"
            />
            <div className="text-xs">
              <p className="font-bold text-base-content truncate">{title}</p>
              {username && (
                <p className="text-base-content/70 truncate">作者: {username}</p>
              )}
            </div>
          </div>
        </foreignObject>
      )}
    </g>
  );
};

export default SVGMagnifierTooltip;